<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta content="user-scalable=no,width=device-width, initial-scale=1" id="viewport" name="viewport" initial-scale="1">

		<script language="javascript" type="text/javascript" src="../js/js/baseJs.js"></script>

	</head>
	<body style="background:#f5f9ff">

		<div class="trading-center-wrapper" id="myJzzBusiness">
			<div class="wap-header" style="background: #323848;">我的交易
				<a class="back" onClick="javascript:window.history.back();return false;"></a>
			</div>
			<div style="color: firebrick;font-size: .24rem;text-align: center;position: relative;background: #f5deca;padding: .1rem;margin: 1rem .4rem 0 .4rem;border-radius: .3rem;">请一定确保收到准确货款后再点击发码</div>
			<div class="tab-c" style="top:0;padding-top: .2rem;">
				
				<div style="display: flex;flex-direction: row;justify-content: space-between;align-items: center;width: 100%;">
					<div style="display: flex;flex-direction: row;">
						<div class="tab" style="width: 2.2rem;" :class="{on:currentType=='2'}" @click="showSaleData()">我的出售</div>
						<div class="tab" style="width: 2.2rem;" :class="{on:currentType=='1'}" @click="showBuyData()">我的求购</div>
					</div>
					<a style="font-size: .24rem;margin-right: .2rem;" href="./jzzDetail.mobile.html">交易记录</a>
				</div>
			</div>
			<div class="my-item-wrapper" style="margin-top: 0.2rem;" id="itemScrollContent">
				<div class="item-c" v-for="item in currentBusinessData">
					<div class="title-c">
						<div style="display: flex;flex-direction: row;">

							<!-- <div class="name" v-else>***</div> -->
							<div class="ico"></div>
							<div class="name" style="margin-left: .1rem;">{{item.status|status}}</div>
						</div>
						<div class="time">{{item.createTime|formatData}}</div>
					</div>
					<div class="number">订单号：{{item.no}}</div>
					<div class="number">出售数量：{{item.jzzNumber}}枚</div>
					<div class="line-c">
						<div>价格：</div>
						<div class="price">￥{{getSellTotalPrice(goldSeedAccountData.currentPrice,item.jzzNumber)}}</div>
					</div>
					<div class="line-c">
						<div class="ico-c">
							<div class="yinglian"></div>
						</div>
						<div style="display: flex;flex-direction: row;" v-if="currentType=='2'">
							<div class="buy-btn" @click="cancelSellJzz(item)" v-if="item.status=='0'||item.status=='1'">取消出售</div>
							<div class="buy-btn" @click="confirmSell(item)" style="margin-left: .3rem;" v-if="item.status=='2'">发码</div>
							<div class="buy-btn" @click="lookUploadImage(item)" style="margin-left: .3rem;">查看凭证</div>
						</div>
						<div v-if="currentType=='1'" style="display: flex;flex-direction: row;">
							<div class="buy-btn" @click="showInputMd5(item)" style="margin-right: .2rem;" v-if="item.status=='2'">输入交易码</div>
							<div class="buy-btn" @click="showAccountInfo(item)" v-if="item.status!=='0'">打款账号</div>
							<div class="buy-btn" @click="showBuyInfo(item)" v-if="item.status=='1'||item.status=='2'" style="margin-left: .1rem;">上传凭证</div>			
						</div>
					</div>
				</div>
			</div>
			<div class="black-background" v-if="showPopupInpueKey||showBuyJzzInfo||isShowBigImage||isshowAccountInfo" @click="showPopupInpueKey=false,inputMd5='',showBuyJzzInfo=false,isShowBigImage=false,isshowAccountInfo=false"></div>
			<div class="sale-jzz" v-if="showPopupInpueKey">
				<div class="sale-number">
					<div class="title-c">密钥</div>
					<div class="right-c">
						<input v-model="inputMd5">
					</div>
				</div>
				<div class="confirm-bt" @click="confirmCheckDone()">确定</div>
			</div>
			<div class="sale-jzz" v-if="isshowAccountInfo">
				<div class="sale-number">
					<div class="title-c">银行名称</div>
					<div class="right-c">{{currentBuyJzzInfo.accountType}}</div>
				</div>
				<div class="sale-number">
					<div class="title-c">银行卡号</div>
					<div class="right-c">{{currentBuyJzzInfo.account}}</div>
				</div>
				<div class="sale-number">
					<div class="title-c">姓名</div>
					<div class="right-c">{{currentBuyJzzInfo.accountName}}</div>
				</div>				
			</div>
			<div class="sale-jzz" v-if="showBuyJzzInfo">
				<div class="sale-number">
					<div class="title-c">付款凭证</div>
					<div style="display:flex;flex-direction:row">
						<div class="upload-wrap">
							<div class="box" v-if="payImgTempList.length==0">
								<label class="p dotted">
									<input type="file" accept="image/*" name="file" @change="onChooseImage($event,3)">
									<img src="../image/add_ico.png" alt="">
								</label>
							</div>
							<template v-for="(imgIndex,imgItem) in payImgTempList">
								<div class="box">
									<div class="image-c">
										<img :src="imgItem">
										<div class="delete" @click.stop="deleteImg(imgIndex,payImgTempList)">
											<img src="../image/close_ico.png" alt="">
										</div>
									</div>
								</div>
							</template>
						</div>
					</div>
				</div>
				<div class="confirm-bt" @click="confirmUpLoadImage">确定</div>
			</div>
			<div style="width: 80%;position: fixed;margin: 0 auto;z-index: 100;    z-index: 100;top: 5%;left: 10%;" v-if="isShowBigImage">
				<img style="width: 100%;" :src="currentSellJzzData.payVoucher" />
			</div>
			<!--  压缩图片用的  -->
			<canvas id="compressCanvas" style="position: fixed; z-index: -1; opacity: 0; top: -100%; left: -100%"></canvas>
		</div>
		<script src="../js/js/rem_fix.js"></script>
		<script src="../js/js/common.js"></script>
		<script type="text/javascript">
			var token = getCookie("userToken");
			var userId = getCookie("userId");
			var accountType = getCookie("accountType");
			var projectId = parseInt(window.location.hash.split("#")[1]);
			var loginUrl = "../userBundle/login.mobile.html";

			var myJzzBusinessApp = new Vue({
				el: '#myJzzBusiness',
				data: {
					currentType: '2',
					currentBusinessData: '',
					goldSeedAccountData: '',
					isLoding: false,
					isDoing: false,
					showPopupInpueKey: false,
					currentSelected: '',
					inputMd5: '',
					showBuyJzzInfo:false,
					payImgTempList: [], // 凭证  图片临时路径列表
					payImgUrlList: [], //凭证 存放七牛返回地址列表
					qiniuData: {
						key: "",
						token: ""
					},
					upload_qiniu_addr: '',
					isDoingUpload:false,
					currentBuyJzzData:'',
					currentBuyJzzInfo:'',
					currentSellJzzData:'',
					isShowBigImage:false,
					isshowAccountInfo:false

				},
				ready: function() {
					if (!token || !userId) {
						window.location.href = loginUrl;
					}
					this.fetchMyJzzBusiness();
					this.fetchJzzData();
					this.qiniuFetch()
				},
				filters: {
					formatData: function(key) {
						return formatDate(key)
					},
					status: function(key) {
						// 0 创建 1锁定 2上传  3 成交 9取消 
						key = parseInt(key);
						var map = {
							0: '创建中',
							1: '等待支付(锁定)',
							2:'已付款',
							3: '成交',
							9: '已取消'
						}
						return map[key];
					}
				},
				methods: {
					qiniuFetch: function() {
						var qiNiuData = {
							client: 1,
							token: token,
							userId: parseInt(userId)
						}
						pushData("/qiniu/get_token ", qiNiuData, function(res) {
							if (res.state) {
								this.qiniuData.token = res.data.result;
								console.log(res)
							} else if (res.errorCode == 008) {
								window.location.href = loginUrl;
							} else {
								alert(res.message)
							}
						}.bind(this));
						pushData("/qiniu/get_image_rul", qiNiuData, function(res) {
							if (res.state) {
								this.upload_qiniu_addr = res.data.url;
								console.log(res)
							} else if (res.errorCode == 008) {
								window.location.href = loginUrl;
							} else {
								alert(res.message)
							}
						}.bind(this));
					},
					showAccountInfo:function(item){
						this.isshowAccountInfo = true;
						this.currentBuyJzzInfo = JSON.parse(item.payInfoJson)[0];
					},			
					lookUploadImage:function(item){
						this.currentSellJzzData=item;
						this.isShowBigImage=true;
						console.log(this.isShowBigImage)
					},
					fetchMyJzzBusiness: function() {
						if (this.isLoding) {
							return
						}
						this.isLoding = true
						var url = '';
						var data = {
							client: 1,
							token: token,
							userId: parseInt(userId)
						}
						if (this.currentType == '2') {
							url = '/jzz/mySaleBusiness'
						} else {
							url = '/jzz/myBuyBusiness'
						}
						pushData(url, data, function(res) {
							console.log(res)
							this.isLoding = false
							if (res.state) {
								this.currentBusinessData = res.data.result;
							} else if (res.errorCode == 008) {
								window.location.href = loginUrl;
							} else {
								alert(res.message)
							}
						}.bind(this))
					},
					showBuyInfo: function(item) {
						this.showBuyJzzInfo = true;
						console.log(item)
						//this.currentBuyJzzInfo = JSON.parse(item.payInfoJson)[0];
						this.currentBuyJzzData = item
					},
					getSellTotalPrice:function(price,number){
						return (price*number).toFixed(5)
					},
					showSaleData: function() {
						this.currentType = '2'
						this.fetchMyJzzBusiness()
					},
					showBuyData: function() {
						this.currentType = '1'
						this.fetchMyJzzBusiness()
					},
					showInputMd5: function(item) {
						this.showPopupInpueKey = true;
						this.currentSelected = item
					},
					confirmSell: function(item) {
						var msg = "确保您已收到款，系统将会发送交易密钥给买家";
						if (confirm(msg) == true) {
							this.isDoing = true;
							var url = '/jzz/sendMa'
							var data = {
								client: 1,
								token: token,
								id: item.id,
								userId: parseInt(userId)
							}
							pushData(url, data, function(res) {
								console.log(res)
								this.isDoing = false
								if (res.state) {
									alert("系统将以短线发送密钥给买家")
								} else if (res.errorCode == 008) {
									window.location.href = loginUrl;
								} else {
									alert(res.data.result)
								}
							}.bind(this))
						} else {
							return false;
						}
						if (this.isDoing) {
							return
						}



					},
					confirmCheckDone: function() {
						if (this.isDoing) {
							return
						}
						this.isDoing = true;
						var url = "/jzz/checkDone";
						var data = {
							client: 1,
							token: token,
							md5: this.inputMd5,
							id: this.currentSelected.id,
							userId: parseInt(userId)
						}
						pushData(url, data, function(res) {
							this.isDoing = false
							if (res.state) {
								alert("交易成功")
								window.location.href = "./goldSeedCenter.html"
							} else if (res.errorCode == 008) {
								window.location.href = loginUrl;
							} else {
								alert(res.message)
							}
						}.bind(this))
					},
					cancelSellJzz: function(item) {
						if (this.isDoing) {
							return
						}
						this.isDoing = true;
						var url = "/jzz/saleCancel";
						var data = {
							client: 1,
							token: token,
							id: item.id,
							userId: parseInt(userId)
						}
						pushData(url, data, function(res) {
							console.log(res)
							this.isDoing = false
							if (res.state) {
								this.fetchMyJzzBusiness()
							} else if (res.errorCode == 008) {
								window.location.href = loginUrl;
							} else {
								alert(res.data.result)
							}
						}.bind(this))

					},
					fetchJzzData: function() {
						var url = "/jzz/flow/user/getUserJzzInfo";
						var data = {
							client: 1,
							token: token,
							id: parseInt(userId),
							userId: parseInt(userId)
						}
						pushData(url, data, function(res) {
							if (res.state) {
								this.goldSeedAccountData = res.data.userInfo;
							} else {
								alert(res.message)
							}
						}.bind(this))
					},
					//选择图片
					onChooseImage: function(event, type) {
						var that = this;
						//判断图片数量是否已上限
					
						var currentImgTempArray = [];
						if (currentImgTempArray.length >= 5) {
							alert("最多上传5张图片");
							return false;
						}
					
						//使用FileReader对文件对象进行操作
						var reader = new FileReader();
						reader.readAsDataURL(event.target.files[0]); //将读取到的文件编码成Data URL
						console.log(event.target.files[0])
					
						reader.onload = function() { //读取完成时
							var replaceSrc = reader.result; //文件输出的内容
							//console.log(reader)
							//压缩图片处理
							var image = new Image();
							image.src = replaceSrc;
							image.onload = function() {
								//获取图片初始宽高
								var width = image.width;
								var height = image.height;
								//判断图片宽度，再按比例设置宽度和高度的值
								if (width > 1024) {
									width = 1024;
									height = Math.ceil(1024 * (image.height / image.width));
								}
					
								//将图片重新画入canvas中
								var canvas = document.getElementById("compressCanvas");
								var context = canvas.getContext("2d");
								canvas.width = width;
								canvas.height = height;
								context.beginPath();
								context.fillStyle = "#ffffff";
								context.fillRect(0, 0, width, height);
								context.fill();
								context.closePath();
								context.drawImage(image, 0, 0, width, height);
								replaceSrc = canvas.toDataURL("image/jpeg"); //canvas转DataURL(base64格式)
					
								//将压缩后的路径 追加到临时路径数组中
								var totalList = [];
								if (currentImgTempArray.length > 0) {
									totalList = currentImgTempArray.concat(replaceSrc);
								} else {
									totalList[0] = replaceSrc;
								}
								that.payImgTempList = totalList
					
								that.onUploadImg(totalList, type)
								//console.log(that.imgTempList)
							};
						};
					
					},
					onUploadImg: function(totalList, type) {
						var that = this;
						console.log(totalList)
						if (totalList.length > 0) {
					
							that.isUploading = true; //正在上传 显示遮罩层 防止连续点击
					
							var countNum = 0; //计算数量用的 判断上传到第几张图片了
					
							//map循环遍历上传图片
							totalList.map(function(imgItem, imgIndex) {
								var files = that.dataURLtoFile(imgItem, 'pj' + Date.now() + '.jpg'); //DataURL转File
								that.qiniuData.key = files.name;
								var formData = new FormData();
								formData.append('token', that.qiniuData.token)
								formData.append('key', that.qiniuData.key) //key为名称
								formData.append('file', files)
								// formData.token=that.qiniuData.token;
								//
								// formData.append("k1", "v1")							
								// formData.get("k1"); // "v1"
								console.log(formData)
								$.ajax({
									type: 'POST',
									url: 'http://upload.qiniup.com',
									contentType: false,
									data: formData,
									processData: false,
									async: false, //设置格式为同步非异步 不然可能会报错无法存储到临时变量/对象
									dataType: 'json',
									success: function(r) {
										console.log(r);
										//that.firstImgUrlList.push(that.upload_qiniu_addr + "/" + r.key);
										that.payImgUrlList.push(that.upload_qiniu_addr + "/" + r.key);
									},
									error: function(r) {
										console.log(r);
									}
								})
							});
						}
					},
					//删除某张图片
					deleteImg: function(idx, imageList) {
						var that = this;
						imageList.splice(idx, 1);
						this.payImgUrlList = []
					},
					
					/**
					 * 将base64转换为文件
					 * @dataUrl base64路径地址
					 * @fileName 自定义文件名字
					 * */
					dataURLtoFile: function(dataUrl, fileName) {
						var arr = dataUrl.split(','),
							mime = arr[0].match(/:(.*?);/)[1],
							bstr = atob(arr[1]),
							n = bstr.length,
							u8arr = new Uint8Array(n);
						while (n--) {
							u8arr[n] = bstr.charCodeAt(n);
						}
						return new File([u8arr], fileName, {
							type: mime
						});
					},
					confirmUpLoadImage: function() {
						if (this.isDoingUpload) {
							return
						}
						
						this.isDoingUpload = true;
						var url = "/jzz/toBuyUploadVoucher"
						if (!this.payImgUrlList[0]) {
							alert("请先转账并截图上传凭证后购买")
							return
						}
						var data = {
							client: "1",
							id: this.currentBuyJzzData.id,
							payVoucher: this.payImgUrlList[0],
							token: token,
							userId: parseInt(userId)
						}
						console.log(data)
						pushData(url, data, function(res) {
							this.isDoingUpload = false;
							if (res.state) {
								alert("已上传凭证，等待卖家确认")
								window.location.href = "./goldSeedCenter.html"
							} else {
								alert(res.data.result)
							}
						}.bind(this))
					},
				}
			})
		</script>

	</body>
</html>
